package com.lds.erp.order.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dph.common.utils.service.BaseOrder;
import com.lds.erp.mch.mch.MchInfoFacade;
import com.lds.erp.mch.mch.order.MchInfoByMchIdOrder;
import com.lds.erp.mch.mch.order.MchInfoByMchMobileOrder;
import com.lds.erp.mch.mch.result.MchInfoResult;
import com.lds.erp.order.enums.ReturnStatusEnum;
import com.lds.erp.order.order.ao.*;
import com.lds.erp.order.order.order.*;
import com.lds.erp.order.order.result.*;
import com.lds.erp.order.order.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dph.common.utils.base.BaseController;
import com.dph.common.utils.base.PageEntity;
import com.dph.common.utils.utils.AppUtils;
import com.lds.erp.base.JsonResult;
import com.lds.erp.common.AppEnum;
import com.lds.erp.common.YNEnum;
import com.lds.erp.common.util.AccountCache;
import com.lds.erp.common.util.AccountUtils;
import com.lds.erp.order.OrderOrderClient;
import com.lds.erp.order.enums.PaymentMethodEnum;
import com.lds.erp.util.DateUtil;
import com.lds.erp.util.JsonUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuli
 */
@RestController
@Api(value = "订单操作", description = "订单操作", tags = { "订单操作接口" })
@RequestMapping(value = "/api/order/order/")
public class OrderController extends BaseController {
	private final static Logger logger = LoggerFactory.getLogger(OrderController.class);
	@Autowired
	private OrderOrderClient orderOrderClient;

	@Reference(version = "1.0")
	private MchInfoFacade mchInfoFacade;

	@ApiOperation(value = "创建订单", notes = "创建订单")
	@PostMapping("mch_create")
	public JsonResult<OrderMchOrderCreateVO> mchCreate(@RequestBody OrderMchOrderCreateAO ao) {

		//预售订单
		if ("Y".equals(ao.getPresale())) {
			String mchCreateOrderOrderStr = JSONObject.toJSONString(ao);
			MchCreatePresaleOrderOrder order = JSON.parseObject(mchCreateOrderOrderStr, MchCreatePresaleOrderOrder.class);
			order.setSerialNo(AppUtils.newNo());
			order.setCartOrderSource(AppEnum.MCHMP);
			AccountCache accountCache = AccountUtils.getAccount();
			MchInfoByMchIdOrder mchId = new MchInfoByMchIdOrder();
			mchId.setMchId(ao.getMchId());
			mchId.setSerialNo(order.getSerialNo());
			MchInfoResult result =  mchInfoFacade.findMchInfo(mchId);
			if (result.getMchInfo().getMchId() != null)
			{
				order.setCartMchId(result.getMchInfo().getMchId());
				order.setCartMchName(result.getMchInfo().getMchName());

				order.setCurrentUserId(result.getMchInfo().getMchId());
				order.setCurrentUserName(result.getMchInfo().getMchName());
				order.setEntrustUserId(accountCache.getMchId());
			}
			else
			{
				return JsonUtils.fail("没有找到电话相应用户");
			}
			order.setCurMchId(accountCache.getMchId());
			MchCreatePresaleOrderResult resultPresale = orderOrderClient.mchCreatePresaleOrder(order);
			return resultPresale.isSuccess() ? JsonUtils.success(resultPresale, OrderMchOrderCreateVO.class)
					: JsonUtils.fail(resultPresale.getMessage());
		}

		String mchCreateOrderOrderStr = JSONObject.toJSONString(ao);
		MchCreateOrderOrder order = JSON.parseObject(mchCreateOrderOrderStr, MchCreateOrderOrder.class);
		order.setSerialNo(AppUtils.newNo());
		order.setCartOrderSource(AppEnum.MCHMP);
		AccountCache accountCache = AccountUtils.getAccount();
		String curMchId = accountCache.getMchId();
		if (ao.getAgent() != null &&  ao.getAgent() == 1)
		{
			if (ao.getMchId() != null)
			{
				MchInfoByMchIdOrder mchId = new MchInfoByMchIdOrder();
				mchId.setMchId(ao.getMchId());
				mchId.setSerialNo(order.getSerialNo());
				MchInfoResult result =  mchInfoFacade.findMchInfo(mchId);
				if (result.getMchInfo().getMchId() != null)
				{
					order.setCartMchId(result.getMchInfo().getMchId());
					order.setCartMchName(result.getMchInfo().getMchName());

					order.setCurrentUserId(result.getMchInfo().getMchId());
					order.setCurrentUserName(result.getMchInfo().getMchName());
					order.setEntrustUserId(curMchId);
					order.setAgent(ao.getAgent());
				}
				else
				{
					return JsonUtils.fail("没有找到电话相应用户");
				}
			}
			else
			{
				return JsonUtils.fail("代客下单，电话不能为空");
			}
		}
		else
		{

			AccountUtils.cacheAccount(accountCache);

			order.setCartMchId(accountCache.getMchId());
			order.setCartMchName(accountCache.getMchName());

			order.setCurrentUserId(accountCache.getMchId());
			order.setCurrentUserName(accountCache.getMchName());
		}

		order.setCurMchId(curMchId);

		MchCreateOrderResult result = orderOrderClient.mchCreateOrder(order);
		return result.isSuccess() ? JsonUtils.success(result, OrderMchOrderCreateVO.class)
				: JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "去付款（生成订单以后）", notes = "去付款")
	@PostMapping("mch_pay")
	public JsonResult<OrderMchOrderPayVO> mchPay(@RequestBody OrderMchOrderPayAO ao) {
		MchCreateOrderPayOrder order = new MchCreateOrderPayOrder();

		BeanUtils.copyProperties(ao, order);
		order.setSerialNo(AppUtils.newNo());
		order.setCartOrderSource(AppEnum.MCHMP);


		if (ao.getAgent() != null  &&  ao.getAgent() == 1)
		{
			if (ao.getMchId() != null)
			{
				MchInfoByMchIdOrder mchId = new MchInfoByMchIdOrder();
				mchId.setMchId(ao.getMchId());
				mchId.setSerialNo(order.getSerialNo());
				MchInfoResult result =  mchInfoFacade.findMchInfo(mchId);
				order.setCartMchId(ao.getMchId());
				order.setCurrentUserId(ao.getMchId());
				if (result != null && result.getMchInfo() != null && result.getMchInfo().getMchName() != null)
				{
					order.setCurrentUserName(result.getMchInfo().getMchName());
				}
				else
				{
					JsonUtils.fail("代理客户昵称没有找到");
				}

			}
			else
			{
				JsonUtils.fail("代理下单客户id不能为空");
			}
		}
		else
		{
			AccountCache accountCache = AccountUtils.getAccount();
			order.setCartMchId(accountCache.getMchId());
			order.setCurrentUserId(accountCache.getMchId());
			order.setCurrentUserName(accountCache.getMchName());
		}


		MchOrderPayResult result = orderOrderClient.mchOrderPay(order);
		return result.isSuccess() ? JsonUtils.success(result, OrderMchOrderPayVO.class)
				: JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "订单详情", notes = "订单详情")
	@GetMapping("detail")
	public JsonResult<OrderMchOrderDetailVO> detail(OrderMchOrderDetailAO ao) {

		AppletOrderDetailOrder order = new AppletOrderDetailOrder();
		BeanUtils.copyProperties(ao, order);
		order.setSerialNo(AppUtils.newNo());
		AppletOrderDetailResult result = orderOrderClient.appletOrderDetail(order);
		return result.isSuccess() ? JsonUtils.success(result, OrderMchOrderDetailVO.class)
				: JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "预售订单详情", notes = "预售订单详情")
	@GetMapping("presale_detail")
	public JsonResult<PresaleOrderDetailVO> presaleDetail(PresaleOrderDetailAO ao) {

		PresaleOrderDetailOrder order = new PresaleOrderDetailOrder();
		BeanUtils.copyProperties(ao, order);
		order.setSerialNo(AppUtils.newNo());
		PresaleOrderDetailResult result = orderOrderClient.queryPresaleDetail(order);
		return result.isSuccess() ? JsonUtils.success(result, PresaleOrderDetailVO.class)
				: JsonUtils.fail(result.getMessage());
	}


	@ApiOperation(value = "订单列表", notes = "订单列表")
	@GetMapping("list")
	public JsonResult<OrderAppletOrderQueryVO> list(OrderAppletOrderQueryAO ao,HttpServletRequest httpRequest) {

		AppletOrderQueryOrder order = new AppletOrderQueryOrder();
		AccountCache accountCache = null;
		accountCache = AccountUtils.getAccount();

		if (accountCache == null )
		{
			String token = httpRequest.getHeader("token");

			if (token != null)
			{
				accountCache = AccountUtils.getAccount(token);
			}

		}


		BeanUtils.copyProperties(ao, order);
		order.setMchId(accountCache.getMchId());
		order.setPage(new PageEntity(ao.getPageNum(), ao.getPageSize()));
		order.setSerialNo(AppUtils.newNo());
		AppletOrderQueryResult result = orderOrderClient.appletOrderQuery(order);
		return result.isSuccess() ? JsonUtils.success(result, OrderAppletOrderQueryVO.class)
				: JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "订单取消", notes = "订单取消")
	@PostMapping("cancel")
	public JsonResult cancel(@RequestBody OrderAppletOrderCancelAO ao) {
		OrderCancelOrder order = new OrderCancelOrder();
		AccountCache accountCache = AccountUtils.getAccount();
		order.setMchId(accountCache.getMchId());
		order.setCurrentUserId(accountCache.getMchId());
		order.setCurrentUserName(accountCache.getMchName());
		order.setOrdOrderNo(ao.getOrdOrderNo());
		order.setSerialNo(AppUtils.newNo());
		OrderCancelResult result = orderOrderClient.orderCancelByOrdOrderNo(order);
		return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "申请退货", notes = "申请退货")
	@PostMapping("apply_return")
	public JsonResult applyReturn(@RequestBody OrderApplyReturnAO ao) {
		OrderApplyReturnOrder order = new OrderApplyReturnOrder();
		BeanUtils.copyProperties(ao, order);
		AccountCache accountCache = AccountUtils.getAccount();
		order.setSerialNo(AppUtils.newNo());
		order.setOrdOrderMchId(accountCache.getMchId());
		order.setOrdOrderMchName(accountCache.getMchName());
		OrderApplyReturnResult result = orderOrderClient.orderApplyReturn(order);
		return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "确认收货", notes = "确认收货")
	@PostMapping("receive")
	public JsonResult receive(@RequestBody OrderAppletOrderCancelAO ao) {
		OrderConfirmReceiveOrder order = new OrderConfirmReceiveOrder();
		AccountCache accountCache = AccountUtils.getAccount();
		BeanUtils.copyProperties(ao, order);
		order.setCurrentUserId(accountCache.getMchId());
		order.setCurrentUserName(accountCache.getMchName());
		order.setSerialNo(AppUtils.newNo());
		OrderConfirmReceiveResult result = orderOrderClient.orderConfirmReceive(order);
		return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
	}

	@ApiOperation(value = "获取配送时间段", notes = "获取配送时间段")
	@GetMapping("send_time")
	public JsonResult<OrdOrderSendTimeVO> sendTime(HttpServletRequest httpRequest) {
		AccountCache accountCache = AccountUtils.getAccount();
		Integer districtId = 0;
		try {
			if (!ObjectUtils.isEmpty(httpRequest.getParameter("districtId")))
			{
				districtId =  Integer.parseInt(httpRequest.getParameter("districtId"));
			}
			else
			{
				districtId =  500112;
			}
		} catch (Exception e) {
			districtId =  500112;
		}
		OrderSendTimeOrder order = new OrderSendTimeOrder();
		order.setSerialNo(AppUtils.newNo());
		order.setDistrictId(districtId);
		order.setMchId(accountCache.getMchId());
		OrderSendTimeResult result = orderOrderClient.orderSendTime(order);
		return result.isSuccess() ? JsonUtils.success(result, OrdOrderSendTimeVO.class)
				: JsonUtils.fail(result.getMessage());

	}

	@ApiOperation(value = "完成之前退货", notes = "完成之前退货")
	@PostMapping("arrive")
	public JsonResult arrive(@RequestBody OrderArriveAO ao) {
		AccountCache accountCache = AccountUtils.getAccount();
		String orderArriveOrderStr = JSONObject.toJSONString(ao);
		OrderArriveOrder order = JSON.parseObject(orderArriveOrderStr, OrderArriveOrder.class);
		order.setCurrentUserId(accountCache.getMchId());
		order.setCurrentUserName(accountCache.getMchName());
		order.setSerialNo(AppUtils.newNo());
		order.setAutoExamine(YNEnum.N);
		order.setOrdPaymentMethod(PaymentMethodEnum.CASH.getCode());
		OrderArriveResult result = orderOrderClient.orderArriveByOrdOrderNo(order);
		return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
	}


	@ApiOperation(value = "退货订单预计算", notes = "退货订单预计算")
	@PostMapping("return_compute")
	public JsonResult<ReturnComputeVO>  returnCompute(@RequestBody ReturnComputeAO ao) {
		String orderArriveOrderStr = JSONObject.toJSONString(ao);
		ReturnComputeOrder order = JSON.parseObject(orderArriveOrderStr, ReturnComputeOrder.class);
		order.setSerialNo(AppUtils.newNo());
		//	商户端需要审核
		order.setAutoExamine(YNEnum.Y);
		ReturnComputeResult result = orderOrderClient.returnComputeByOrdOrderNo(order);
		return result.isSuccess() ? JsonUtils.success(result, ReturnComputeVO.class)
				: JsonUtils.fail(result.getMessage());
	}


	@ApiOperation(value = "退货列表查询", notes = "退货列表查询")
	@GetMapping("return_list")
	public JsonResult<OrderReturnQueryVO> returnList(OrderApplyReturnQueryAO ao) {

		QueryOrderReturnOrder order = new QueryOrderReturnOrder();
		order.setSerialNo(AppUtils.newNo());
		order.setPage(new PageEntity(ao.getPageNum(), ao.getPageSize()));
		List<ReturnStatusEnum> returnStatus=new ArrayList<>();
		AccountCache accountCache = AccountUtils.getAccount();
		order.setReturnMchId(accountCache.getMchId());
		if (ao.getReturnStatus().equals("PENDING")){
			returnStatus.add(ReturnStatusEnum.PENDING);
			order.setReturnStatus(returnStatus);
		}else{
			returnStatus.add(ReturnStatusEnum.PASS);
			returnStatus.add(ReturnStatusEnum.CANCEL);
			order.setReturnStatus(returnStatus);
		}
		QueryOrderReturnResult result = orderOrderClient.queryOrderReturn(order);
		return result.isSuccess() ? JsonUtils.success(result, OrderReturnQueryVO.class)
				: JsonUtils.fail(result.getMessage());
	}
	@ApiOperation(value = "退货详情", notes = "退货详情")
	@GetMapping("return_detail")
	public JsonResult<ReturnDetailVO>  returnDetail( OrderReturnDetailAO ao) {
		QueryOrderReturnDetailOrder order = new QueryOrderReturnDetailOrder();
		BeanUtils.copyProperties(ao, order);
		order.setSerialNo(AppUtils.newNo());
		QueryOrderReturnDetailResult result = orderOrderClient.queryOrderReturnDetail(order);
		return result.isSuccess() ? JsonUtils.success(result, ReturnDetailVO.class)
				: JsonUtils.fail(result.getMessage());
	}




	@ApiOperation(value = "聚合支付测试", notes = "聚合支付测试")
	@GetMapping("jhpay_info")
	public JsonResult<JhPayInfoVO> jh() {
		BaseOrder order=new BaseOrder();
		order.setSerialNo(AppUtils.newNo());
		OrderJhPayResult result = orderOrderClient.jhInfo(order);
		return result.isSuccess() ? JsonUtils.success(result, JhPayInfoVO.class)
				: JsonUtils.fail(result.getMessage());
	}

}
